package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.config.RGroupAppConfig;
import ar.republicagroup.gestion.entities.Banco;
import ar.republicagroup.gestion.entities.CuentaBanco;
import ar.republicagroup.gestion.entities.CuentaTipo;
import ar.republicagroup.gestion.services.BancoServices;
import ar.republicagroup.gestion.services.CuentaBancoServices;
import ar.republicagroup.gestion.services.CuentaTipoServices;
import ar.republicagroup.gestion.util.JComboBoxModel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.Validar;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class modalPanelAddCuentaBanco extends javax.swing.JDialog {
    
    BancoServices        bancoServices        = (BancoServices)SpringUtils.getBean("bancoServices");
    CuentaTipoServices   cuentaServices       = (CuentaTipoServices)SpringUtils.getBean("cuentaTipoServices");
    CuentaBancoServices  cuentaBancoServices  = (CuentaBancoServices)SpringUtils.getBean("cuentaBancoServices");
    
    private static final int ULTIMO = 1;
    private static final int NO_ULTIMO = 0;

    public modalPanelAddCuentaBanco(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setIconImage(new ImageIcon(getClass().getResource(RGroupAppConfig.getProperty("iconForFramesPath"))).getImage());
        cargarDatos();
        
    }

   
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelNuevaCuenta = new javax.swing.JPanel();
        txtNombre = new javax.swing.JTextField();
        txtNroCuenta = new javax.swing.JTextField();
        txtCBU = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        comboTipoCuenta = new javax.swing.JComboBox();
        comboBanco = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btnRegistrar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        lblErrorNombre = new javax.swing.JLabel();
        lblErrorNroCuenta = new javax.swing.JLabel();
        lblErrorCBU = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("...Alta de cuenta bancaria...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        panelNuevaCuenta.setBorder(javax.swing.BorderFactory.createTitledBorder("Nueva cuenta bancaria"));

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
        });

        txtNroCuenta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNroCuentaKeyPressed(evt);
            }
        });

        txtCBU.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCBUKeyPressed(evt);
            }
        });

        jLabel1.setText("Nombre");

        jLabel2.setText("Nro.Cuenta");

        jLabel3.setText("CBU");

        comboBanco.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N

        jLabel4.setText("Banco");

        jLabel5.setText("Tipo de cuenta");

        btnRegistrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/add.png"))); // NOI18N
        btnRegistrar.setText("Registrar");
        btnRegistrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        lblErrorNombre.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorNombre.setText("(*)Campo obligatorio");

        lblErrorNroCuenta.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorNroCuenta.setText("(*)Campo obligatorio");

        lblErrorCBU.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorCBU.setText("(*)Campo obligatorio");

        javax.swing.GroupLayout panelNuevaCuentaLayout = new javax.swing.GroupLayout(panelNuevaCuenta);
        panelNuevaCuenta.setLayout(panelNuevaCuentaLayout);
        panelNuevaCuentaLayout.setHorizontalGroup(
            panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelNuevaCuentaLayout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelNuevaCuentaLayout.createSequentialGroup()
                        .addComponent(btnRegistrar)
                        .addGap(18, 18, 18)
                        .addComponent(btnCancelar))
                    .addGroup(panelNuevaCuentaLayout.createSequentialGroup()
                        .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(comboBanco, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(txtNroCuenta)
                            .addComponent(txtNombre)
                            .addComponent(txtCBU)
                            .addComponent(comboTipoCuenta, 0, 140, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblErrorNombre)
                            .addComponent(lblErrorNroCuenta)
                            .addComponent(lblErrorCBU))))
                .addContainerGap(141, Short.MAX_VALUE))
        );
        panelNuevaCuentaLayout.setVerticalGroup(
            panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelNuevaCuentaLayout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboBanco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboTipoCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(lblErrorNombre))
                .addGap(18, 18, 18)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNroCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblErrorNroCuenta)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCBU, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(lblErrorCBU))
                .addGap(18, 18, 18)
                .addGroup(panelNuevaCuentaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRegistrar)
                    .addComponent(btnCancelar))
                .addContainerGap(49, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelNuevaCuenta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(43, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelNuevaCuenta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnRegistrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarActionPerformed
        /*VALORES DE LOS COMBOS*/
        JComboBoxModel modelComboTipo   = (JComboBoxModel)comboTipoCuenta.getSelectedItem();
        JComboBoxModel modelComboBanco  = (JComboBoxModel)comboBanco.getSelectedItem();
        
        CuentaBanco cuenta = new CuentaBanco();
        cuenta.setNombre(txtNombre.getText());
        cuenta.setNumero(txtNroCuenta.getText());
        cuenta.setCbu(txtCBU.getText());
        cuenta.setCuentaTipoId(cuentaServices.get(Integer.valueOf(modelComboTipo.getValue())));
        cuenta.setBancoId(bancoServices.get(Integer.valueOf(modelComboBanco.getValue())));
        cuenta.setEstado(1);
        String mensaje = cuentaBancoServices.insert(cuenta);
        
        if(mensaje != null){
            JOptionPane.showMessageDialog(this, mensaje, "Registro exitoso", JOptionPane.INFORMATION_MESSAGE);
            int resp = JOptionPane.showConfirmDialog(this, "Desea registrar otra cuenta?", "Confirme", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            
                    if (resp == 0){
                        limpiarFormulario();
                    }else{
                        dispose();
                    }
       }else {
            JOptionPane.showMessageDialog(this, "Se produjo un error al insertar", "Error", JOptionPane.ERROR_MESSAGE);
        }
  
    }//GEN-LAST:event_btnRegistrarActionPerformed

    private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
        if(evt.getKeyCode() == evt.VK_ENTER){
            validarCajaDeTexto(txtNombre.getText(), txtNombre, lblErrorNombre, txtNroCuenta,NO_ULTIMO);
        }
    }//GEN-LAST:event_txtNombreKeyPressed

    private void txtNroCuentaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNroCuentaKeyPressed
       if(evt.getKeyCode() == evt.VK_ENTER){
            validarCajaDeTexto(txtNroCuenta.getText(), txtNroCuenta, lblErrorNroCuenta, txtCBU,NO_ULTIMO);
        }
    }//GEN-LAST:event_txtNroCuentaKeyPressed

    private void txtCBUKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCBUKeyPressed
        if(evt.getKeyCode() == evt.VK_ENTER){
            validarCajaDeTexto(txtCBU.getText(), txtCBU, lblErrorCBU, null,ULTIMO);
        }
    }//GEN-LAST:event_txtCBUKeyPressed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
       frmCuentaBanco.cargarTablaReportes(cuentaBancoServices.findEntities());
    }//GEN-LAST:event_formWindowClosed

    private void cargarDatos(){
       txtNombre.requestFocus();
       comboBanco.setModel(bancoServices.combo());    
       comboTipoCuenta.setModel(cuentaServices.combo());
       
       /*Labels de mensajes de validación*/
       lblErrorNombre.setVisible(false);
       lblErrorNroCuenta.setVisible(false);
       lblErrorCBU.setVisible(false);
    }
    
    public void limpiarFormulario(){
        txtNombre.setText("");
        txtNroCuenta.setText("");
        txtCBU.setText("");
        
        lblErrorNombre.setVisible(false);
        lblErrorNroCuenta.setVisible(false);
        lblErrorCBU.setVisible(false);
        
        comboBanco.setSelectedIndex(0);
        comboTipoCuenta.setSelectedIndex(0);
        
        txtNombre.requestFocus();
    }
    
    
    /*VALIDACIONES*/
    
    private void validarCajaDeTexto(String texto,JTextField cajita,JLabel labelDeError,JTextField siguiente_focus,int ultimo){
         if(!Validar.esVacio(texto) && !Validar.validarVacio(texto)){
             if(ultimo == 0){   
                siguiente_focus.requestFocus();
                }
                labelDeError.setVisible(false);
         }else{
                cajita.requestFocus();
                labelDeError.setVisible(true);
         }
    }
    
    
    
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddCuentaBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddCuentaBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddCuentaBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(modalPanelAddCuentaBanco.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                modalPanelAddCuentaBanco dialog = new modalPanelAddCuentaBanco(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnRegistrar;
    private javax.swing.JComboBox comboBanco;
    private javax.swing.JComboBox comboTipoCuenta;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel lblErrorCBU;
    private javax.swing.JLabel lblErrorNombre;
    private javax.swing.JLabel lblErrorNroCuenta;
    private javax.swing.JPanel panelNuevaCuenta;
    private javax.swing.JTextField txtCBU;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtNroCuenta;
    // End of variables declaration//GEN-END:variables
}
